<template>
  <Wrapper>
    <el-card shadow="never">
      <el-button link type="primary" icon="View" @click="open"
        >查看文档</el-button
      >
      <dynamic-form
        ref="formRef"
        :items="items"
        :model="defaultValue"
        :rules="rules"
      >
        <template #prefix>
          <el-icon name="User" />
        </template>
      </dynamic-form>
      <el-button type="primary" @click="getValue">获取值</el-button>
      <el-button @click="reset">重置</el-button>
      <el-button type="warning" @click="validate">form校验</el-button>
      <el-button type="primary" @click="addItem">增加一项</el-button>
      <el-button type="danger" @click="removeItem"
        >删除一项(根据prop)</el-button
      >
      <el-button @click="getAllFields">获取所有fields</el-button>
    </el-card>
    <el-card v-if="formData" shadow="never" style="margin-top: 13px">
      {{ formData }}
    </el-card>

    <docs-modal v-model="visible" />
  </Wrapper>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import useModal from '@/hooks/useModal'
import DynamicForm from '@/components/form'
import DocsModal from '../components/docs-modal'
import configs from './config.jsx'
console.log(configs)

const { visible, open } = useModal()

const formRef = ref(null)
const formData = ref(null)
const defaultValue = ref({
  name: '初始值---default',
  place: '',
  transportation: 'self-driving',
  enable: 'open',
  foods: ['option2'],
  date: '2025-01-18',
  time: '12:00:00',
})
const items = ref([...configs])
const rules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  place: [{ required: true, message: '请选择地点', trigger: 'change' }],
  transportation: [
    { required: true, message: '请选择交通方式', trigger: 'change' },
  ],
  foods: [
    {
      validator: (rule, value, callback) => {
        if (value.length < 2) {
          callback(new Error('至少选择两种食物'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
})

function getValue() {
  console.log(formRef.value.getValues())
  formData.value = JSON.stringify(formRef.value.getValues())
}

function getAllFields() {
  ElMessage.success('打开哦控制台查看')
  console.log(formRef.value.fields)
}

function reset() {
  formRef.value.resetFields()
  formData.value = null
}

function validate() {
  formRef.value.validate()
}

function addItem() {
  formRef.value.addItem({
    label: '新增项',
    prop: 'newField',
    component: 'input',
    value: '',
    rule: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    componentProps: {
      placeholder: '请输入内容',
      type: 'textarea',
      rows: 6,
      prefixIcon: 'Bell',
    },
  })
}

function removeItem() {
  formRef.value.removeItem('newField')
}
</script>
